#include "clipboard.h"
#include "protocol.h"
#include <QApplication>
#include <QClipboard>
#include <QMimeData>
#include <QTimer>

ClipboardService::ClipboardService(QObject *parent)
    : QObject(parent)
    , localClipboard(QApplication::clipboard())
    , protocol(nullptr)
    , enabled(true)
    , ignoreChanges(false)
    , sendTimer(new QTimer(this))
{
    setupClipboard();
    
    // 设置发送定时器，避免频繁发送
    sendTimer->setSingleShot(true);
    sendTimer->setInterval(500); // 500ms延迟
    connect(sendTimer, &QTimer::timeout, this, &ClipboardService::sendClipboardToRemote);
}

ClipboardService::~ClipboardService()
{
}

void ClipboardService::setProtocol(Protocol *protocol)
{
    this->protocol = protocol;
}

void ClipboardService::setEnabled(bool enabled)
{
    this->enabled = enabled;
}

bool ClipboardService::isEnabled() const
{
    return enabled;
}

void ClipboardService::updateLocalClipboard(const QString &text)
{
    if (!enabled || !localClipboard)
        return;
        
    ignoreChanges = true;
    localClipboard->setText(text);
    lastText = text;
    ignoreChanges = false;
}

void ClipboardService::clearClipboard()
{
    if (!enabled || !localClipboard)
        return;
        
    ignoreChanges = true;
    localClipboard->clear();
    lastText.clear();
    ignoreChanges = false;
}

void ClipboardService::onLocalClipboardChanged()
{
    if (!enabled || !localClipboard || ignoreChanges)
        return;
        
    const QMimeData *mimeData = localClipboard->mimeData();
    if (mimeData && mimeData->hasText()) {
        QString text = mimeData->text();
        if (text != lastText) {
            lastText = text;
            // 启动定时器，延迟发送
            sendTimer->start();
        }
    }
}

void ClipboardService::sendClipboardToRemote()
{
    if (!enabled || !protocol || lastText.isEmpty())
        return;
        
    // 发送剪贴板内容到远程
    // 在实际实现中，这里会调用协议特定的剪贴板更新方法
    emit protocol->clipboardUpdated(lastText);
}

void ClipboardService::setupClipboard()
{
    if (localClipboard) {
        connect(localClipboard, &QClipboard::changed, 
                this, &ClipboardService::onLocalClipboardChanged);
    }
}